package base;

import listener.DefaultBaseFlowListener;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Listeners;
import common.utils.ConfUtils;
import common.utils.LeoLogger;

import java.util.concurrent.TimeUnit;


@Listeners({DefaultBaseFlowListener.class})
public abstract class BaseFlow {
    public WebDriver driver = null;
    public String environment;
    public String browser;

    public BaseFlow() {
        this.environment = System.getProperty("environment");
        this.browser = System.getProperty("browser");
    }

    public WebDriver getDriver() {
        return driver;
    }

    @BeforeClass
    public void setUp() {
        setupBrowser();
    }

    @AfterClass
    public void tearDown() {
        LeoLogger.logCaseStep("close WebDriver");
        if (driver != null) {
            driver.quit();
        }
    }

    public void setupBrowser() {
        this.driver = setupBrowser(this.driver, this.browser);
    }

    public WebDriver setupBrowser(WebDriver driver, String browser) {
        LeoLogger.logCaseStep("setUp Browser, init WebDriver");
        if (driver != null) {
            try {
                driver.quit();
            } catch (Exception e) {
                LeoLogger.warn("quit driver exception", e);
            }
        }
        switch (browser.toLowerCase()) {
            case "firefox":
                System.setProperty("webdriver.gecko.driver", "src/main/resources/driver/geckodriver.exe");
                driver = new FirefoxDriver();
                break;
            case "ie11":
                System.setProperty("webdriver.ie.driver", "src/main/resources/driver/IEDriverServer.exe");
                driver = new InternetExplorerDriver();
                break;
            default:
                System.setProperty("webdriver.chrome.driver", "src/main/resources/driver/chromedriver.exe");
                driver = new ChromeDriver();
        }
        driver.manage().timeouts().pageLoadTimeout(ConfUtils.getDefaultPageTimeout(), TimeUnit.SECONDS);
        driver.manage().timeouts().implicitlyWait(ConfUtils.getDefaultElementTimeout(), TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.manage().deleteAllCookies();
        return driver;
    }
}
